package com.hook3.pianke.activity.base.radiouserbasepager;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;


import com.google.gson.Gson;
import com.hook3.pianke.Net.Url;
import com.hook3.pianke.R;
import com.hook3.pianke.activity.base.radiouserbasepager.PrivateRadioViewpagerBase.PrivateRadioViewpager1;
import com.hook3.pianke.activity.base.radiouserbasepager.PrivateRadioViewpagerBase.PrivateRadioViewpager2;
import com.hook3.pianke.activity.base.radiouserbasepager.PrivateRadioViewpagerBase.PrivateRadioViewpager3;
import com.hook3.pianke.activity.base.radiouserbasepager.PrivateRadioViewpagerBase.PrivateRadioViewpager4;
import com.hook3.pianke.activity.base.radiouserbasepager.PrivateRadioViewpagerBase.PrivateRadioViewpagerBasePager;
import com.hook3.pianke.activity.base.radiouserbasepager.RadioService.MusicRadioService;
import com.hook3.pianke.domain.PrivateRadioInfo;
import com.hook3.pianke.domain.RadioPlayerViewPagerInfo;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.Serializable;
import java.util.ArrayList;


/**
 * 播放音频的viewpager页面
 */
public class RadioViewPagerActivity extends AppCompatActivity implements View.OnClickListener {
    Toolbar toolbar;
    ViewPager mViewPager;
    private static final String VIEWPAGERURL = "http://api2.pianke.me/ting/info";

    //当前播放列表和歌曲id
    ArrayList<PrivateRadioInfo.PrivateRadioEachContent>  privateRadiolist;
    int playMusicPosition;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_radio_viewpager);

        initToolbar();

        //得到intent中的数据
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        privateRadiolist = (ArrayList<PrivateRadioInfo.PrivateRadioEachContent>) bundle.getSerializable("privateRadiolist");
        playMusicPosition = intent.getIntExtra("position", -1);

        initView();
        initData();
        //启动音乐播放器服务
        bindServiceAtActivity();
        mViewPager.setCurrentItem(1);


        //初始化listener
        initListener();
    }

    /**
     * 初始化view
     */
    ImageButton mStartAndPause;
    public void initView(){
        mStartAndPause = (ImageButton) findViewById(R.id.iv_private_radio_view_pager_start);
    }

    /**
     * 初始化toolbar
     */
    public void initToolbar(){
        toolbar = (Toolbar) findViewById(R.id.tb_radio_view_pager_toolbar);
        LinearLayout fourIcon = (LinearLayout) View.inflate(this,R.layout.imageview_private_radio_view_pager_toolbar_four_icon,null);
        toolbar.addView(fourIcon);

        fourIcon.measure(0, 0);
        Log.e("TAG","fourIcon.getMeasuredWidth() + =======" + fourIcon.getMeasuredWidth());
        int leftPadding = toolbar.getWidth() - fourIcon.getMeasuredWidth();

        Log.e("TAG","toolbar.getWidth()======" + toolbar.getWidth());
        Log.e("TAG","leftPadding======" + leftPadding);
        fourIcon.setPadding(150, 0, 0, 0);

        toolbar.setTitle("");
        mViewPager = (ViewPager) findViewById(R.id.vp_radio_view_pager_viewpager);
        setSupportActionBar(toolbar);

        toolbar.setNavigationIcon(R.mipmap.abc_ic_ab_back_mtrl_am_alpha);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }


    //初始化viewpager四个页面
    ArrayList<PrivateRadioViewpagerBasePager> pagerList;
    //初始化数据
    private void initData() {

        //请求数据
        getDataFromNet();

        pagerList = new ArrayList<PrivateRadioViewpagerBasePager>();

    }

    /**
     * 请求数据
     */
    RadioPlayerViewPagerInfo radioPlayerViewPagerInfo;
    private void getDataFromNet(){
        RequestParams requestparams = new RequestParams(VIEWPAGERURL);
        requestparams.addBodyParameter("tingid",privateRadiolist.get(playMusicPosition).tingid);
        requestparams.addBodyParameter("client", "2");
        x.http().post(requestparams, new Callback.CacheCallback<String>() {

            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                radioPlayerViewPagerInfo = gson.fromJson(result, RadioPlayerViewPagerInfo.class);

                pagerList.add(new PrivateRadioViewpager1(RadioViewPagerActivity.this, privateRadiolist));
                pagerList.add(new PrivateRadioViewpager2(RadioViewPagerActivity.this, radioPlayerViewPagerInfo));
                pagerList.add(new PrivateRadioViewpager3(RadioViewPagerActivity.this, radioPlayerViewPagerInfo));
                pagerList.add(new PrivateRadioViewpager4(RadioViewPagerActivity.this, radioPlayerViewPagerInfo));

                //给Viewpager设置adapter
                mViewPager.setAdapter(new PagerAdapter() {
                    @Override
                    public int getCount() {
                        return pagerList.size();
                    }

                    @Override
                    public boolean isViewFromObject(View view, Object object) {
                        return view == object;
                    }

                    @Override
                    public Object instantiateItem(ViewGroup container, int position) {
                        pagerList.get(position).initData();
                        container.addView(pagerList.get(position).view);

                        return pagerList.get(position).view;
                    }

                    @Override
                    public void destroyItem(ViewGroup container, int position, Object object) {
                        container.removeView((View) object);
                    }
                });
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }

            @Override
            public boolean onCache(String result) {
                return false;
            }
        });
    }

    /**
     * 启动音乐播放器服务
     */
    private void bindServiceAtActivity() {
        Intent intent = new Intent(RadioViewPagerActivity.this,
                MusicRadioService.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("privateRadiolist", privateRadiolist);
        intent.putExtras(bundle);
        startService(intent);
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
    }

    //服务中间人
    MusicRadioService.Middle middleService;
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            middleService = (MusicRadioService.Middle) service;
            middleService.openAudio(playMusicPosition);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    /**
     * 初始化listener
     */
    private void initListener(){
        mStartAndPause.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(v == mStartAndPause){
            startAndPause();
        }
    }

    private void startAndPause(){
        if(middleService != null){
            if(middleService.isPlaying()){
                middleService.pause();
            }else{
                middleService.start();
            }
        }
    }

}
